const mxItem = require('./mx-item');
import {
  nxValidator
} from '../../components/nx-validator';

module.exports = Behavior({
  behaviors: ['wx://form-field', mxItem],
  properties: {
    /** 之所以将所有信息以对象的方式传入，是为了后面的数据验证 */
    props: {
      type: Object,
      observer(props) {
        this.setData({
          label: props.label,
          required: props.required,
          pattern: props.pattern || '',
          errorMessage: props.errorMessage || '',
          placeholder: (props.placeholder || '请选择' + props.label) + (props.required ? '（必填）' : ''),
          title: '选择' + props.label, //默认值
        });
      }
    },
    // 选项
    columns: {
      type: Array,
      value: [],
    },
    // 是否展示关键字搜索
    showKeyWordSearch: {
      type: Boolean,
      value: true,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    title: '',
    show: false,
    text: '',
    // 默认选中项的索引
    defaultIndex: -1,
    /** 当前的选项 */
    columnsCurrent: [],
    /** 来自后端配置的选项，具有优先权 */
    columnsFromConfig: [],
  },

  methods: {
    /** 弹出选择框 */
    showPicker() {
      this.setData({
        show: true
      });
    },
    /** 取消选择框 */
    cancel: function () {
      this.setData({
        show: false
      });
    },
    /** 确认选择器 */
    confirm: function (e) {
      const { text, value } = e.detail.value;
      const { value: valuePrev, name } = this.data;
      const d = this.data;

      this.setData({
        show: false,
        text,
        value,
      });

      // 验证数据
      nxValidator(d, value).then(() => {
        this.setData({
          errorMessage: d.errorMessage,
        });
      });

      if (value && value !== valuePrev) {
        this.triggerEvent("change", {
          field: name,
          ...e.detail.value,
        });
      }
    },
    // 搜索关键字
    search(e) {
      const _v = e.detail.value, {
        columns,
        columnsFromConfig
      } = this.data;
      let c = [];

      // 来自后端配置的选项，具有优先权
      if (columnsFromConfig && columnsFromConfig.length > 0) {
        c = columnsFromConfig;
      } else {
        c = columns;
      }

      this.setData({
        columnsCurrent: c.filter(i => i.text.indexOf(_v) > -1),
      });
    }
  },
})